<script setup lang="ts">
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import type {
  BalanceAlarm,
  BalanceAlarmQueryRequest,
} from "@/models/balanceAlarm";
import {
  listBalanceAlarmByPage,
  addBalanceAlarm,
  updateBalanceAlarm,
  deleteBalanceAlarm,
} from "@/api/balanceAlarm";
import dayjs from "dayjs";

// 表格数据
const dataSource = ref<BalanceAlarm[]>([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(6);

// 搜索条件
const searchForm = ref({
  dormitoryId: undefined,
  equipmentId: undefined,
  isSolved: undefined,
  dateRange: [],
});

// 编辑弹窗
const editModalVisible = ref(false);
const editingRecord = ref<BalanceAlarm>({
  id: undefined,
  dormitoryId: undefined,
  equipmentId: undefined,
  isSolved: 0,
  note: "",
  deviceBalance: 0,
});
const isAdd = ref(false);

// 获取数据列表
const fetchRecords = async () => {
  loading.value = true;
  try {
    const queryRequest: BalanceAlarmQueryRequest = {
      current: currentPage.value,
      pageSize: pageSize.value,
      dormitoryId: searchForm.value.dormitoryId,
      equipmentId: searchForm.value.equipmentId,
      isSolved: searchForm.value.isSolved,
      startDate: searchForm.value.dateRange?.[0]
        ? dayjs(searchForm.value.dateRange[0]).format("YYYY-MM-DD")
        : undefined,
      endDate: searchForm.value.dateRange?.[1]
        ? dayjs(searchForm.value.dateRange[1]).format("YYYY-MM-DD")
        : undefined,
    };
    const res = await listBalanceAlarmByPage(queryRequest);
    if (res.data.code === 0) {
      dataSource.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      message.error("获取数据失败");
    }
  } catch (error) {
    message.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 处理表格变化
const handleTableChange = (pagination: any) => {
  currentPage.value = pagination.current;
  pageSize.value = pagination.pageSize;
  fetchRecords();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchRecords();
};

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    dormitoryId: undefined,
    equipmentId: undefined,
    isSolved: undefined,
    dateRange: [],
  };
  currentPage.value = 1;
  fetchRecords();
};

// 添加记录
const handleAdd = () => {
  isAdd.value = true;
  editingRecord.value = {
    id: undefined,
    dormitoryId: undefined,
    equipmentId: undefined,
    isSolved: 0,
    note: "",
    deviceBalance: 0,
    alarmDate: undefined,
  };
  editModalVisible.value = true;
};

// 编辑记录
const handleEdit = (record: BalanceAlarm) => {
  isAdd.value = false;
  editingRecord.value = {
    ...record,
    alarmDate: record.alarmDate ? dayjs(record.alarmDate) : undefined,
  };
  editModalVisible.value = true;
};

// 保存记录
const handleSave = async () => {
  try {
    const submitData = {
      ...editingRecord.value,
      alarmDate: editingRecord.value.alarmDate
        ? dayjs(editingRecord.value.alarmDate).format("YYYY-MM-DD")
        : undefined,
    };

    if (isAdd.value) {
      const res = await addBalanceAlarm(submitData);
      if (res.data.code === 0) {
        message.success("添加成功");
      } else {
        message.error("添加失败");
        return;
      }
    } else {
      const res = await updateBalanceAlarm(submitData);
      if (res.data.code === 0) {
        message.success("更新成功");
      } else {
        message.error("更新失败");
        return;
      }
    }
    editModalVisible.value = false;
    fetchRecords();
  } catch (error) {
    message.error("操作失败");
  }
};

// 删除记录
const handleDelete = async (id: number) => {
  try {
    const res = await deleteBalanceAlarm({ id });
    if (res.data.code === 0) {
      message.success("删除成功");
      fetchRecords();
    } else {
      message.error("删除失败");
    }
  } catch (error) {
    message.error("删除失败");
  }
};

onMounted(() => {
  fetchRecords();
});
</script>

<template>
  <div class="balance-alarm-management">
    <!-- 搜索表单 -->
    <a-card class="search-card">
      <a-form layout="inline">
        <a-form-item label="宿舍号">
          <a-input-number
            v-model:value="searchForm.dormitoryId"
            placeholder="请输入宿舍号"
          />
        </a-form-item>
        <a-form-item label="设备号">
          <a-input-number
            v-model:value="searchForm.equipmentId"
            placeholder="请输入设备号"
          />
        </a-form-item>
        <a-form-item label="处理状态">
          <a-select
            v-model:value="searchForm.isSolved"
            placeholder="请选择状态"
            allowClear
          >
            <a-select-option :value="0">未处理</a-select-option>
            <a-select-option :value="1">已处理</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="报警日期">
          <a-range-picker
            v-model:value="searchForm.dateRange"
            :placeholder="['开始日期', '结束日期']"
            style="width: 240px"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">搜索</a-button>
            <a-button @click="handleReset">重置</a-button>
            <a-button type="primary" @click="handleAdd">添加记录</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 数据表格 -->
    <a-card class="table-card">
      <a-table
        :dataSource="dataSource"
        :loading="loading"
        :pagination="{
          total,
          current: currentPage,
          pageSize,
          showSizeChanger: true,
          showQuickJumper: true,
        }"
        @change="handleTableChange"
      >
        <a-table-column title="宿舍号" dataIndex="dormitoryId" />
        <a-table-column title="设备号" dataIndex="equipmentId" />
        <a-table-column title="设备余额" dataIndex="deviceBalance" />
        <a-table-column title="处理状态" dataIndex="isSolved">
          <template #default="{ text }">
            <a-tag :color="text === 1 ? 'green' : 'red'">
              {{ text === 1 ? "已处理" : "未处理" }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="备注" dataIndex="note" />
        <a-table-column
          title="报警日期"
          dataIndex="alarmDate"
          :customRender="
            ({ text }) => (text ? dayjs(text).format('YYYY-MM-DD') : '-')
          "
        />
        <a-table-column
          title="创建时间"
          dataIndex="createTime"
          :customRender="
            ({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
          "
        />
        <a-table-column title="操作" key="action">
          <template #default="{ record }">
            <a-space>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这条记录吗？"
                @confirm="handleDelete(record.id)"
              >
                <a>删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table-column>
      </a-table>
    </a-card>

    <!-- 编辑弹窗 -->
    <a-modal
      v-model:visible="editModalVisible"
      :title="isAdd ? '添加记录' : '编辑记录'"
      @ok="handleSave"
    >
      <a-form :model="editingRecord" layout="vertical">
        <a-form-item label="宿舍号" required>
          <a-input-number
            v-model:value="editingRecord.dormitoryId"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="设备号" required>
          <a-input-number
            v-model:value="editingRecord.equipmentId"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="设备余额" required>
          <a-input-number
            v-model:value="editingRecord.deviceBalance"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="处理状态">
          <a-select v-model:value="editingRecord.isSolved">
            <a-select-option :value="0">未处理</a-select-option>
            <a-select-option :value="1">已处理</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="报警日期">
          <a-date-picker
            v-model:value="editingRecord.alarmDate"
            style="width: 100%"
            :placeholder="'请选择报警日期'"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea v-model:value="editingRecord.note" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.balance-alarm-management {
  padding: 24px;
}

.search-card {
  margin-bottom: 24px;
}

.table-card {
  background: #fff;
}

:deep(.ant-card-body) {
  padding: 24px;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}
</style>
